from datetime import datetime, timedelta
from sqlalchemy import text
import pandas as pd
from urllib.parse import unquote_plus
import json
#from scipy.interpolate import interp1d
import numpy as np
import random,os
#用于Y轴
def find_and_modify(data, target_key,target_name, mx,mn,unit,color,pcs,grp):
    """
        如果找到目标元素，则返回其在列表中的位置；否则，返回-1。
    """
    for i, item in enumerate(data):
        if item.get(target_key) == target_name:
            if mx != None and item['max'] != 'auto':
                item['max'] = max(item['max'],mx)
                item['_max'] = max(item['_max'],mx)
            else:
                item['max'] = 'auto'
            
            if mn != None and item['min'] != 'auto':
                item['min'] = min(item['min'],mn)
                item['_min'] = min(item['_min'],mn)
            else:
                item['min'] = 'auto'
             
            #单位设置给名 Y轴曲线
            # if grp:
            item['name'] = f"{grp}\n{unit}"
            # else:
            # item['name'] = f"\n{unit}"
                
                
            item['axisLine']['color'] = color
            item['pcs'] = max(item['pcs'],pcs)#最大精度
            return i
    return -1

#随机颜色
def random_color_code():
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)
    color_code = '#{:02x}{:02x}{:02x}'.format(r, g, b)
    return color_code


def generate_time_array(n=20, hours=2):
    return []
    # 计算起始时间和时间间隔
    end_time = datetime.now()
    start_time = end_time - timedelta(hours=hours)
    interval = (end_time - start_time) / (n - 1)

    # 生成时间数组
    time_array = []
    for i in range(n):
        time = start_time + i * interval
        time_array.append(time.strftime('%Y-%m-%d %H:%M:%S'))

    # 返回时间数组
    return time_array

def getBatchNo():
    return 'bm_BatchNo'

def is_raspberry_pi():
    try:
        with open('/proc/cpuinfo', 'r') as f:
            cpuinfo = f.read()
        return 'Raspberry Pi' in cpuinfo
    except Exception as e:
        print(f"Error: {e}")
        return False

def getFilesPath():
    if is_raspberry_pi():
        return '/home/pi/Project/build/cproPy/files'
    return os.path.join(os.getcwd(),'files')

def read_sql(query_sql, conn):
    result = conn.execute((query_sql))
    df = pd.DataFrame(result.fetchall(), columns=result.keys())
    return df

def reindex_nearest_n(df, new_index, n):
    # 使用 method='nearest' 重新索引 DataFrame
    nearest_df = df.reindex(new_index, method='nearest')

    # 计算新索引与原始索引之间的距离
    distances = np.abs(nearest_df.index.values - np.array(new_index).reshape(-1, 1))

    # 创建一个布尔掩码，以保留距离在最近的 n 个元素之内的数据
    mask = distances <= np.sort(distances, axis=1)[:, :n].max(axis=1).reshape(-1, 1)

    # 使用布尔掩码从原始 DataFrame 中选择所需的数据，并填充其余部分为 NaN
    result_df = nearest_df.where(mask, np.NaN)

    return result_df

def generate_smooth_random_curve(min_value=-1, max_value=1,n=20):
    return []
    # # 生成随机点
    # x = np.linspace(0, 1, n)
    # y = np.random.uniform(min_value, max_value, n)

    # # 使用样条插值生成平滑曲线
    # f = interp1d(x, y, kind='cubic')
    # x_new = np.linspace(0, 1, n)
    # y_new = f(x_new)

    # # 将值缩放到指定范围
    # y_new = (y_new - np.min(y_new)) / (np.max(y_new) - np.min(y_new))
    # y_new = y_new * (max_value - min_value) + min_value

    
    # # 四舍五入到小数点后 3 位 narray转成list
    # y_new = [round(val, 3) for val in y_new]

    # # 返回数组
    # return y_new

def format_num(number, precision):
    """
    将数字格式化为指定位数的精度
    :param number: 要格式化的数字
    :type number: float
    :param precision: 精度
    :type precision: int
    :return: 格式化后的数字
    :rtype: str
    """
    return "{:.{}f}".format(number, precision)


def any_element_in_common(list1, list2):
    return any(element in list2 for element in list1)


def find_values(json_obj, key):
    results = []

    def _extract_values(obj, key):
        """Recursively search for values of key in JSON tree."""
        if isinstance(obj, dict):
            for k, v in obj.items():
                if k == key:
                    results.append(v)
                elif isinstance(v, (dict, list)):
                    _extract_values(v, key)
        elif isinstance(obj, list):
            for item in obj:
                _extract_values(item, key)

    _extract_values(json_obj, key)
    return results

# 增加单引号和逗号进行连接
def add_quotes(string):
    elements = string.split(",")
    quoted_elements = [f"'{elem}'" for elem in elements]
    result = ",".join(quoted_elements)
    return result


def urlDecode(code):
    # 检查 "fields" 是否包含 "urlDecode"
    if 'urlDecode' in code:
        # 找到 "urlDecode(" 和 ")" 的位置
        start = code.find('urlDecode(')
        end = code.find(')', start)
        if start != -1 and end != -1:
            # 获取并解码 "urlDecode(" 和 ")" 之间的部分
            encoded_part = code[start+10:end]
            decoded_part = unquote_plus(encoded_part)
            # 将JSON字符串转换为Python对象
            decode = json.loads(decoded_part)
            # 将解码后的部分和其他部分一起返回
            return code[:start] + decode + code[end+1:]
    # 如果没有 "urlDecode(" 或 ")", 直接返回原字符串
    return code


if __name__ == '__main__':
    # 生成随机曲线
    y = generate_smooth_random_curve()

    # 绘制曲线
    x = range(len(y))
    # plt.plot(x, y, 'r-', label='Curve')
    # plt.legend()
    # plt.show()
